package com.edu.controller;

import com.edu.entity.Product;
import com.edu.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Repository;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@RestController
@RequestMapping("products")
public class ProductController {

    @Autowired
    private ProductService productService;

    @PostMapping
    public ResponseEntity<Product> addProduct(@Valid Product product){
        Product result = productService.addProduct(product);
        return new ResponseEntity<Product>(result,HttpStatus.OK);
    }

    @GetMapping("{id}")
    public ResponseEntity<Product> findOne(@PathVariable Long id){
        Product result = productService.findOne(id);
        return new ResponseEntity<Product>(result,HttpStatus.OK);
    }

    @GetMapping
    public Page<Product> query(String ids,
                               BigDecimal minRewardRate,
                               BigDecimal maxRewardRate,
                               String status,
                               @RequestParam(defaultValue = "0") int pageNum,
                               @RequestParam(defaultValue = "10") int pageSize) {

        List<Long> idList = new ArrayList<>();
        List<String> statusList = new ArrayList<>();

        /**
         * 封装 id 列表
         */
        if (!StringUtils.isEmpty(ids)){
            String[] idStrings =ids.split(",");

            for (String idString : idStrings) {
                Long id = Long.parseLong(idString);
                idList.add(id);
            }
        }
        /**
         * 封装 状态 列表
         */
        if (!StringUtils.isEmpty(status)){
            statusList = Arrays.asList(status.split(","));
        }
        Pageable pageable = new PageRequest(pageNum, pageSize);

        Page<Product> result = productService.query(idList, minRewardRate, maxRewardRate, statusList, pageable);

        return result;
    }

}
